export default class StateMachine {
    protected curState: IState = null;
    protected lastState: IState = null;
    protected states: { [name: string]: IState } = {}

    registerState(name: string | number, state: IState) {
        this.states[name] = state;
        state.onInit();
    }

    changeState(name: string | number) {
        return new Promise((resolve, reject) => {
            const state = this.states[name];
            if (!state) {
                console.error("State not found: ", name);
                return;
            }
            if (this.curState) {
                // if (this.curState.stateName == name) return;
                this.curState.onLeave();
            }
            this.lastState = this.curState;
            this.curState = state;
            state.stateName = name;
            state.onEnter()?.then(resolve);
        });
    }

    update(dt: number) {
        this.curState && this.curState.onUpdate(dt);
    }

    destroy() { }
}